package cn.pku.edu.cs.ldn.thread;

import cn.pku.edu.cs.ldn.util.FileUtil;
import cn.pku.edu.cs.ldn.util.ImageUtil;
import android.graphics.Bitmap;
import android.util.Log;

public class ImageDownloadThread extends HttpDownloadThread {
	private static final String TAG = "ImageDownloadThread";
	private static final boolean DEBUG = true;

	public static final int MODE_AT_MOST = 0;
	public static final int MODE_AROUND = 1;
	int mode = MODE_AT_MOST;
	int width = -1;
	int height = -1;

	public ImageDownloadThread(String url, String path,
			ThreadObserverHandler handler) {
		super(url, path, handler);
	}

	public void setImageSizeLimit(int width, int height, int mode) {
		this.width = width;
		this.height = height;
		this.mode = mode;
	}

	@Override
	public void run() {
		Bitmap b = null;
		if (requestStop == false) {
			if (FileUtil.isLocalFileExist(localPath) == false) {
				boolean downloadRet = download();
				if (downloadRet) {
					if (mode == MODE_AT_MOST) {
						b = ImageUtil.loadBitmapNoBiggerThanRequired(localPath,
								width, height);
					} else {
						b = ImageUtil.loadBitmapAroundRequired(localPath,
								width, height);
					}
				}
			} else {
				if (DEBUG)
					Log.v(TAG, "run: exist " + localPath);
				if (mode == MODE_AT_MOST) {
					b = ImageUtil.loadBitmapNoBiggerThanRequired(localPath,
							width, height);
				} else {
					b = ImageUtil.loadBitmapAroundRequired(localPath, width,
							height);
				}
			}

		}
		notifyFinish(b);
	}
}
